<template>
  <div calss="searchData">
    <el-form :inline="true" :model="searchData" class="demo-form-inline">
      <el-form-item label="站点">
        <el-select
          v-model="searchData.productSite"
          placeholder="请选择站点"
          style="width: 200px"
          clearable
        >
          <el-option
            v-for="(item, index) in productSiteOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="searchData.dataTime"
          type="daterange"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          size="default"
        />
      </el-form-item>
      <el-form-item label="按商品ID">
        <el-input v-model="searchData.productCode" placeholder="请输入商品ID" clearable />
      </el-form-item>
      <el-form-item label="按店铺ID">
        <el-input v-model="searchData.sellerId" placeholder="请输入店铺ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="selectedExport">选中导出</el-button>
        &nbsp;
        <p>已选中{{ allIds.length }}个商品</p>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-table
      class="tableList"
      :data="tableData.data"
      border
      show-overflow-tooltip
      :highlight-current-row="false"
      :header-cell-style="{
        background: '#F3F4F7',
        color: '#272626',
        'font-size': '16px',
      }"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="updatedAt" label="更新时间" />
      <el-table-column prop="productSite" label="站点" />
      <el-table-column prop="productCode" label="商品ID" />
      <el-table-column prop="productTitle" label="商品名称" />
      <el-table-column prop="productUrl" label="商品地址" />
      <el-table-column prop="productMainImg" label="商品主图" width="120">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.productMainImg"
            fit="cover"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="productThumbnail" label="商品缩略图" width="120">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.productThumbnail"
            fit="cover"
          />
        </template>
      </el-table-column> -->
      <el-table-column prop="productPrice" label="商品价格" />
      <el-table-column prop="category1Name" label="一级类目名称" />
      <el-table-column prop="category1Url" label="一级类目地址" />
      <el-table-column prop="category2Name" label="二级类目名称" />
      <el-table-column prop="category2Url" label="二级类目地址" />
      <el-table-column prop="category3Name" label="三级类目名称" />
      <el-table-column prop="category3Url" label="三级类目地址" />
      <el-table-column prop="category4Name" label="四级类目名称" />
      <el-table-column prop="category4Url" label="四级类目地址" />
      <el-table-column prop="productInfo" label="商品信息" />
      <el-table-column prop="productDesc" label="商品描述" />
      <el-table-column prop="sellerId" label="卖家ID" />
      <el-table-column prop="sellerName" label="卖家名称" />
      <el-table-column prop="sellerUrl" label="卖家店铺" />
      <!-- <el-table-column fixed="right" label="操作" width="120">
        <template #default>
          <el-button link type="primary" size="small">编辑</el-button>
          <el-button link type="primary" size="small">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.total"
      :page-sizes="[10, 20, 30, 50]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { getProducts, exportProducts, exportChecked } from "@/api/goodsQuery";
import { ElMessage } from "element-plus";

// 搜索参数
const searchData = reactive({
  productSite: "",
  productCode: "",
  sellerId: "",
  dataTime: "",
});

// 记录开始时间和结束时间
const timer = reactive({
  updatedStartTime: "",
  updatedEndTime: "",
});

// 选择商品id的集合
let selectedIds: any = ref();

let allIds: any = ref([]);

// 页码
const currentPage = ref(1);
// 页数
const pageSize = ref(10);

// 表格数据
const tableData = reactive({
  total: 1000,
  data: [],
});

// 站点下拉值
const productSiteOptions = [
  {
    value: "yahoo",
    label: "yahoo",
  },
  {
    value: "mercari",
    label: "mercari",
  },
];

// 获取表格数据
const getProductsFn = () => {
  const productReq = {
    productSite: searchData.productSite,
    productCode: searchData.productCode,
    sellerId: searchData.sellerId,
    updatedStartTime: timer.updatedStartTime,
    updatedEndTime: timer.updatedEndTime,
  };
  getProducts(productReq, currentPage.value, pageSize.value).then((res) => {
    tableData.data = res.data.records;
    tableData.total = res.data.totalCount;
  });
};

// 点击页数时
function handleSizeChange(val: number) {
  currentPage.value = 1;
  pageSize.value = val;
  timer.updatedStartTime = searchData.dataTime ? getTime(searchData.dataTime[0]) : "";
  timer.updatedEndTime = searchData.dataTime ? getTime(searchData.dataTime[1]) : "";
  getProductsFn();
}

// 点击或跳转页码时
function handleCurrentChange(val: number) {
  currentPage.value = val;
  // 页码改变时 页数不变 重新请求数据
  timer.updatedStartTime = searchData.dataTime ? getTime(searchData.dataTime[0]) : "";
  timer.updatedEndTime = searchData.dataTime ? getTime(searchData.dataTime[1]) : "";
  getProductsFn();
}

// 查询
const handleQuery = () => {
  // console.log("点击查询");
  timer.updatedStartTime = searchData.dataTime ? getTime(searchData.dataTime[0]) : "";
  timer.updatedEndTime = searchData.dataTime ? getTime(searchData.dataTime[1]) : "";
  getProductsFn();
};

// 时间格式化
const getTime = (dt: any) => {
  const year = dt.getFullYear(); //年
  let month = dt.getMonth() + 1; //月
  let date = dt.getDate(); //日
  month = month < 10 ? "0" + month : month;
  date = date < 10 ? "0" + date : date;
  const str = year + "-" + month + "-" + date;
  return str;
};

// 导出
const handleExport = () => {
  const productReq = {
    productSite: searchData.productSite,
    productCode: searchData.productCode,
    sellerId: searchData.sellerId,
    updatedStartTime: timer.updatedStartTime,
    updatedEndTime: timer.updatedEndTime,
  };
  exportProducts(productReq)
    .then((res) => {
      const fileData = res.data;
      const fileName = decodeURI(
        res.headers["content-disposition"].split(";")[1].split("=")[1]
      );
      const fileType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

      const blob = new Blob([fileData], { type: fileType });
      const downloadUrl = window.URL.createObjectURL(blob);

      const downloadLink = document.createElement("a");
      downloadLink.href = downloadUrl;
      downloadLink.download = fileName;

      document.body.appendChild(downloadLink);
      downloadLink.click();

      document.body.removeChild(downloadLink);
      window.URL.revokeObjectURL(downloadUrl);
      ElMessage.success("导出成功");
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

// 点击选择时
let handleSelectionChange = (val: any) => {
  // 记录当前页选中的id
  selectedIds.value = val.map((key: any) => key.id);

  // 合并当前选择与已选择
  allIds.value = [...new Set([...allIds.value, ...selectedIds.value])];
};

// 选中导出
let selectedExport = () => {
  exportChecked(allIds.value)
    .then((res) => {
      const fileData = res.data;
      const fileName = decodeURI(
        res.headers["content-disposition"].split(";")[1].split("=")[1]
      );
      const fileType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

      const blob = new Blob([fileData], { type: fileType });
      const downloadUrl = window.URL.createObjectURL(blob);

      const downloadLink = document.createElement("a");
      downloadLink.href = downloadUrl;
      downloadLink.download = fileName;

      document.body.appendChild(downloadLink);
      downloadLink.click();

      document.body.removeChild(downloadLink);
      window.URL.revokeObjectURL(downloadUrl);
      ElMessage.success("导出成功");
      // 导出成功 值初始化  页数回到第一页
      allIds.value = [];
      handleCurrentChange(1);
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

onMounted(() => {
  getProductsFn();
});
</script>

<style scoped>
.searchData {
  margin-bottom: 20px;
}
.tableList {
  margin-bottom: 20px;
}
</style>
